import time
import logging
import json

import requests

from conf import config
from helper.meituan.sign_helper import SignHelper
from helper.meituan.request_constant import RequestConstant

logger = logging.getLogger("wechat.helper.meituan")


class CreateOrderByShop(object):
    """
    创建美团配送订单类
    """
    def __init__(self, order_id, shop_id, name, addr, phone, lng, lat, seq, weight, goods, fee):
        self.delivery_id = int(order_id)
        self.order_id = order_id
        self.shop_id = shop_id
        self.name = name
        self.address = addr
        self.phone = phone
        self.lng = int(lng * pow(10, 6))
        self.lat = int(lat * pow(10, 6))
        self.poi_seq = seq
        self.goods_weight = weight
        self.goods_detail = goods
        self.goods_value = fee
        self.appkey = config.MEITUAN_APP_KEY
        self.secret = config.MEITUAN_APP_SECRET

    def create_shop_order(self):
        secret = self.secret
        data = self.create_order_data()
        sign = SignHelper.get_sign(data, secret)
        logger.info(f"sign={sign}")
        data["sign"] = sign
        url = RequestConstant.ORDER_CREATE_BY_SHOP
        try:
            response = requests.post(url, data=data, timeout=30)
            response = response.json()
            logger.info(f"response={response}")
            return response
        except Exception as e:
            logger.error(e)
            return False

    def create_order_data(self):
        data = dict(
            timestamp=int(time.time()),
            version="1.0",
            appkey=self.appkey,
            delivery_id=self.delivery_id,
            order_id=self.order_id,
            shop_id=self.shop_id,
            order_type=0,
            delivery_service_code=4011,
            receiver_name=self.name,
            receiver_address=self.address,
            receiver_lng=self.lng,
            receiver_lat=self.lat,
            receiver_phone=self.phone,
            coordinate_type=0,
            expected_delivery_time=int(time.time()) + 3600,
            poi_seq=self.poi_seq,
            goods_weight=self.goods_weight,
            goods_detail=self.goods_detail,
            goods_value=self.goods_value,
        )
        return data


if __name__ == '__main__':
    order_id = "15014114115713553"
    shop_id = "test_0001"
    name = "测试收货人"
    addr = "测试收货人地址"
    phone = "18523657373"
    lng = 97.235458
    lat = 31.065074
    seq = "1"
    weight = 3
    goods = {
        "goods":[
            {
              "goodCount": 1,
              "goodName": "货品名称",
              "goodPrice": 9.99,
              "goodUnit": "个"
            }
        ]
    }
    goods = json.dumps(goods)
    fee = 9.99
    o = CreateOrderByShop(order_id, shop_id, name, addr, phone, lng, lat, seq, weight, goods, fee)
    result = o.create_shop_order()
    print(f"result={result}")